/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.code.motoo.filter;

import java.nio.channels.SocketChannel;
import java.util.HashMap;
import java.util.Map;

import com.google.code.motoo.core.DefaultSingleTask;
import com.google.code.motoo.core.IoBuffer;
import com.google.code.motoo.core.IoSession;
import com.google.code.motoo.core.SingleTask;
import com.google.code.motoo.core.TaskExecutor;
import com.google.code.motoo.filter.IoFilter.NextIoFilter;

/**
 * @author linfengqi
 * @version 1.0
 * @date May 7, 2009
 */
public class DefaultIoFilterChain implements IoFilterChain{
	
	private IoSession session;
	
    private final EntryImpl head;
    private final EntryImpl tail;
    private final Map<String, Entry> name2entry = new HashMap<String, Entry>();
    
    public DefaultIoFilterChain(IoSession session) {
        if (session == null) {
            throw new NullPointerException("session");
        }

        this.session = session;
        head = new EntryImpl(null, null, "head", new HeadFilter());
        tail = new EntryImpl(head, null, "tail", new TailFilter());
        head.nextEntry = tail;
    }

	public void addAfter(String baseName, String name, IoFilter filter) {
		EntryImpl baseEntry = checkOldName(baseName);
        checkAddable(name);
        register(baseEntry, name, filter);
	}

	public void addBefore(String baseName, String name, IoFilter filter) {
		EntryImpl baseEntry = checkOldName(baseName);
        checkAddable(name);
        register(baseEntry.prevEntry, name, filter);
	}

	public void addFirst(String name, IoFilter filter) {
		register(head, name, filter);
	}

	public void addLast(String name, IoFilter filter) {
		register(tail.prevEntry, name, filter);
	}

	public boolean contains(String name) {
		return getEntry(name) != null;
	}

	public boolean contains(IoFilter filter) {
		return getEntry(filter) != null;
	}
	
	public IoFilter getFirst() {
		EntryImpl e = head.nextEntry;
		if (e == tail)
			return null;
		return e.getFilter();
	}

	public IoFilter getLast() {
		EntryImpl e = tail.prevEntry;
		if (e == head)
			return null;
		return e.getFilter();
	}
	

	public IoFilter get(String name) {
		Entry e = getEntry(name);
        if (e == null) {
            return null;
        }

        return e.getFilter();
	}

	public Entry getEntry(String name) {
        Entry e = name2entry.get(name);
        if (e == null) {
            return null;
        }
        return e;
    }

    public Entry getEntry(IoFilter filter) {
        EntryImpl e = head.nextEntry;
        while (e != tail) {
            if (e.getFilter() == filter) {
                return e;
            }
            e = e.nextEntry;
        }
        return null;
    }

	public NextIoFilter getNextFilter(String name) {
		Entry e = getEntry(name);
        if (e == null) {
            return null;
        }

        return e.getNextFilter();
	}

	public NextIoFilter getNextFilter(IoFilter filter) {
		Entry e = getEntry(filter);
        if (e == null) {
            return null;
        }

        return e.getNextFilter();
	}

	public IoFilter remove(String name) {
		EntryImpl entry = checkOldName(name);
        deregister(entry);
        return entry.getFilter();
	}

	public void remove(IoFilter filter) {
		EntryImpl e = head.nextEntry;
        while (e != tail) {
            if (e.getFilter() == filter) {
                deregister(e);
                return;
            }
            e = e.nextEntry;
        }
	}
	
	private EntryImpl checkOldName(String baseName) {
        EntryImpl e = (EntryImpl) name2entry.get(baseName);
        if (e == null) {
            throw new IllegalArgumentException("Filter not found:" + baseName);
        }
        return e;
    }
	
	private void checkAddable(String name) {
        if (name2entry.containsKey(name)) {
            throw new IllegalArgumentException("Other filter is using the same name '" + name + "'");
        }
    }
	
	private void register(EntryImpl prevEntry, String name, IoFilter filter) {
        EntryImpl newEntry = new EntryImpl(prevEntry, prevEntry.nextEntry, name, filter);

        prevEntry.nextEntry.prevEntry = newEntry;
        prevEntry.nextEntry = newEntry;
        name2entry.put(name, newEntry);
    }
	
	private void deregister(EntryImpl entry) {
        EntryImpl prevEntry = entry.prevEntry;
        EntryImpl nextEntry = entry.nextEntry;
        prevEntry.nextEntry = nextEntry;
        nextEntry.prevEntry = prevEntry;

        name2entry.remove(entry.name);
    }
	
	private class HeadFilter extends IoFilterAdapter {

		public void messageSend(NextIoFilter nextFilter, IoSession session, Object message) throws Exception {
			if (!(message instanceof IoBuffer)) throw new RuntimeException("write message is not correct!");
			IoBuffer buffer = (IoBuffer) message;
			SocketChannel channel = session.getSocketChannel();
			if (channel != null && channel.isOpen()) {
				synchronized (channel) {
					channel.write(buffer.buf());
				}
			}
			session.setLastAccessTime();
			
			boolean keepAlive = (Boolean) session.getAttribute(IoSession.KEEP_ALIVE);
			if (!keepAlive) {
				session.getHandler().sessionClosed(session);
				session.close();
			}
			
		}
		
	}
	
	private class TailFilter extends IoFilterAdapter {

		public void messageReceived(NextIoFilter nextFilter, IoSession session, Object message) throws Exception {
			TaskExecutor taskExecutor = (TaskExecutor) session.getAttribute(IoSession.TASK_EXECUTOR);
			SingleTask task = new DefaultSingleTask(session, message);
			taskExecutor.submit(task);
		}

	}
	
	private class EntryImpl implements Entry {
		
		private EntryImpl prevEntry;
        private EntryImpl nextEntry;
        private final String name;
        private final IoFilter filter;
        private final NextIoFilter nextFilter;
        
        private EntryImpl(EntryImpl prevEntry, final EntryImpl nextEntry, final String name, final IoFilter filter) {
            if (filter == null) {
                throw new NullPointerException("filter");
            }
            if (name == null) {
                throw new NullPointerException("name");
            }

            this.prevEntry = prevEntry;
            this.nextEntry = nextEntry;
            this.name = name;
            this.filter = filter;
            this.nextFilter = new NextIoFilter() {

				public void messageReceived(IoSession session, Object message) throws Exception {
					Entry nextEntry = EntryImpl.this.nextEntry;
					IoFilter filter = nextEntry.getFilter();
		            NextIoFilter nextFilter = nextEntry.getNextFilter();
		            filter.messageReceived(nextFilter, session, message);
				}

				public void messageSend(IoSession session, Object message) throws Exception {
					Entry prevEntry = EntryImpl.this.prevEntry;
					IoFilter filter = prevEntry.getFilter();
		            NextIoFilter nextFilter = prevEntry.getNextFilter();
		            filter.messageSend(nextFilter, session, message);
				}
            	
            };
            
        }

		public void addAfter(String name, IoFilter filter) {
			DefaultIoFilterChain.this.addAfter(getName(), name, filter);
		}

		public void addBefore(String name, IoFilter filter) {
			DefaultIoFilterChain.this.addAfter(getName(), name, filter);
		}

		public IoFilter getFilter() {
			return filter;
		}

		public String getName() {
			return name;
		}

		public NextIoFilter getNextFilter() {
			return nextFilter;
		}

		public void remove() {
			DefaultIoFilterChain.this.remove(getName());
		}

	}

}
